// 行为型
// 不同的对象之间划分责任和算法的抽象化

// 命令模式
// 请求以命令的形式包裹在对象中，并传给调用方
// 对于游戏角色的控制
// 接受者
class Receiver {
    execute() {
        console.log('角色开始奔跑')
    }
}

// 触发者
class Operator {
    constructor(command) {
        this.command = command
    }
    run() {
        // 跑。。
        this.command.execute()
    }
}

// 指令器
class Command {
    constructor(receiver) {
        this.receiver = receiver
    }
    execute() {
        this.receiver.execute()
    }
}

const soldier = new Receiver()
const order = new Command(soldier)
const player = new Operator(order)

player.run()

// 观察者模式
// 当一个属性发生状态改变的时候，观察者连续引发所有相关状态的改变，并实时触发
class MediaCenter {
    constructor() {
        this.state = ''
        this.observers = []
    }
    attach(observer) {
        this.observers.push(observer)
    }
    getState() {
        return this.state
    }
    setState(state) {
        this.state = state
        this.notifyAllobservers()
    }
    notifyAllobservers() {
        this.observers.forEach(ob => {
            ob.update()
        })
    }
}

class Observers {
    constructor(name, center) {
        this.name = name
        this.center = center
        this.center.attach(this)
    }
    update() {
        console.log(`${this.name} updated, state: ${this.center.getState()}`)
    }
}

// 职责链
// 1. 链式调用 2.职责彼此独立 3. 顺序执行
class Action {
    constructor(name) {
        this.name = name
        this.nextAction = null
    }
    setNextAction(action) {
        this.nextAction = action
    }
    handle() {
        console.log(`${this.name}请审批，是否可以通过`)
        if(this.nextAction !== null) {
            this.nextAction.handle()
        }
    }
}

const leader = new Action('组长')
const manager = new Action('经理')
const president = new Action('总监')

leader.setNextAction(manger)
manger.setNextAction(president)

leader.handle()

